package com.dingding.order.core.confirm.biz.impl;

import java.math.BigDecimal;

import javax.annotation.Resource;

import org.apache.http.HttpStatus;
import org.apache.log4j.Logger;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import com.dingding.common.core.base.code.BaseCodeMessage;
import com.dingding.common.core.base.dto.AbstractResponse;
import com.dingding.common.core.base.dto.ResponseEntity;
import com.dingding.common.core.beans.UserTaxiOrdert;
import com.dingding.common.core.model.push.PushModel;
import com.dingding.common.core.sms.model.MessageModel;
import com.dingding.common.core.util.DateFormatUtil;
import com.dingding.common.core.util.JSONUtil;
import com.dingding.common.core.util.ToolUtil;
import com.dingding.facade.queue.dto.msg.MessageRequestsDTO;
import com.dingding.facade.queue.dto.push.PushRequestDTO;
import com.dingding.facade.queue.enums.ClientType;
import com.dingding.facade.queue.enums.PushType;
import com.dingding.facade.queue.enums.RoleType;
import com.dingding.facade.queue.facade.IQueueFacade;
import com.dingding.facade.user.service.order.ITaxiConfirmArriveFacade;
import com.dingding.order.code.GrabOrderCodeMsg;
import com.dingding.order.code.order.OrderStatus;
import com.dingding.order.core.confirm.biz.IConfirmArriveService;
import com.dingding.order.core.confirm.dao.ITaxiConfirmArriveOrderDao;
import com.dingding.order.dto.confirm.PushTaxiConfirmArrival;
import com.dingding.order.dto.confirm.ReqTaxiConfirmArriveDTO;
import com.dingding.order.dto.confirm.ResTaxiConfirmArriveDTO;
import com.dingding.order.dto.publish.PushData;

/**
 * 
 * @ClassName: TaxiConfirmArriveServiceImpl 
 * @Description: 出租车确认到达业务逻辑实现类
 * @author YHQ
 * @date 2016年6月29日 下午2:58:18
 * 
 */
@Component("taxiConfirmArriveService")
public class TaxiConfirmArriveServiceImpl extends AbstractResponse<ResTaxiConfirmArriveDTO, ReqTaxiConfirmArriveDTO> implements IConfirmArriveService {

	private Logger log = Logger.getLogger(this.getClass());
	
	@Resource(name="taxiConfirmArriveOrder")
	private ITaxiConfirmArriveOrderDao taxiConfirmArriveOrderDao;
	
	@Resource(name="taxiConfirmArriveFacade")
	private ITaxiConfirmArriveFacade taxiConfirmArriveFacade;
	
	@Resource(name="queueService")
	private IQueueFacade queueFacade;
	
	/**
	 * 
	 * @Title: taxiConfirmArrive 
	 * @Description: 出租车确认到达
	 * @param reqTaxiConfirmArriveDTO  出租车确认到达客户端请求Bean
	 * @author YHQ 
	 * @version V2.3.0
	 * @return String    返回类型
	 * 
	 */
	@Override
	@Transactional(propagation=Propagation.REQUIRED)
	public String confirmArrive(String requestData) {
		
		// 出租车确认到达，响应客户端Bean
		ResponseEntity<ResTaxiConfirmArriveDTO> response = new ResponseEntity<ResTaxiConfirmArriveDTO>();
		
		//客户端请求参数
		ReqTaxiConfirmArriveDTO taxiConfirmArriveDTO = super.parseRequestJson(requestData);
		
		// 验证客户端请求参数
		if(!super.validateParam(response, taxiConfirmArriveDTO)){
			return  super.responseBeanToJson(response);
		}
		
		// 判断传入金额是否大于0
		if(taxiConfirmArriveDTO.getPayMoney().compareTo(new BigDecimal(0)) <= 0){
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(BaseCodeMessage.PAY_MONEY_ERROR);
			response.setPromptMessage(BaseCodeMessage.PAY_MONEY_ERROR);
			return  super.responseBeanToJson(response);
		}
		
		// 获取待确认到达的出租车订单信息，并做相应的确认到达条件判断
		UserTaxiOrdert taxiOrdert = getTaxiOrdert(taxiConfirmArriveDTO.getOid(), response);
		
		// 判断是否符合确认到达条件
		if(taxiOrdert == null){
			return super.responseBeanToJson(response);
		}
		
		// 出租车确认到达操作
		taxiConfirmArrive(taxiOrdert, taxiConfirmArriveDTO, response);
		
		// 通知乘客支付(发送短信、推送消息)
		this.confirmArriveNotice(taxiOrdert,taxiConfirmArriveDTO.getClientType());
		
		return super.responseBeanToJson(response);
	}

	/**
	 * 
	 * @Title: geTaxiOrdert 
	 * @Description: 根据出租车订单Id获取订单信息 
	 * @param oid 订单Id
	 * @author YHQ 
	 * @version V2.3.0
	 * @return UserTaxiOrdert    返回类型
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public UserTaxiOrdert getTaxiOrdert(String oid,ResponseEntity<ResTaxiConfirmArriveDTO> response){
		
		//用于存储出租车订单的对象
		UserTaxiOrdert taxiOrdert = null;
		
		try {
			taxiOrdert = taxiConfirmArriveOrderDao.getUserTaxiOrdertInfoById(oid);
		} catch (Exception e) {
			
			response.setCode(HttpStatus.SC_INTERNAL_SERVER_ERROR);
			response.setErrorMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR); 
			response.setPromptMessage(GrabOrderCodeMsg.GET_TAXI_ORDER_INFO_ERROR_CLIENT);
			log.error("根据出租车订单Id获取订单信息时出现异常   类："+this.getClass()+" geTaxiOrdert()", e);
			return null;
		}
		
		//如果出租车订单不存在，则给出相应的错误信息
		if(taxiOrdert == null){
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
			response.setPromptMessage(GrabOrderCodeMsg.ORDER_NOT_EXISTS);
			return null;
		}else if(taxiOrdert.getOrderStatus() != OrderStatus.ORDER_STATUS_PAY){  // 2:服务中
			response.setCode(HttpStatus.SC_FORBIDDEN);
			response.setErrorMessage(GrabOrderCodeMsg.NOT_CARRIED_OUT_ORDER);
			response.setPromptMessage(GrabOrderCodeMsg.NOT_CARRIED_OUT_ORDER);
			return null;
		}
		
		return taxiOrdert;
	}

	/**
	 * 
	 * @Title: taxiConfirmArrive 
	 * @Description: 出租车确认到达操作 
	 * @param taxiOrdert 出租车订单信息
	 * @param taxiConfirmArriveDTO 出租车确认到达-客户端请求参数
	 * @param response
	 * @author YHQ 
	 * @version V2.3.0
	 * @return void    返回类型
	 * 
	 */
	@Transactional(propagation=Propagation.REQUIRED)
	public void taxiConfirmArrive(UserTaxiOrdert taxiOrdert,ReqTaxiConfirmArriveDTO taxiConfirmArriveDTO,ResponseEntity<ResTaxiConfirmArriveDTO> response){
		
		// 3:待支付
		taxiOrdert.setOrderStatus(OrderStatus.ORDER_STATUS_PAID); 
		// 支付金额
		taxiOrdert.setTotalMoney(taxiConfirmArriveDTO.getPayMoney());
		
		// 创建出租车确认达到响应Bean
		ResTaxiConfirmArriveDTO resTaxiConfirmArriveDTO = new ResTaxiConfirmArriveDTO();
		
		// 订单Id
		resTaxiConfirmArriveDTO.setOid(taxiOrdert.getTaxiOrdertId());	
		// 订单状态
		resTaxiConfirmArriveDTO.setOrderStatus(taxiOrdert.getOrderStatus());	
		
		response.setCode(HttpStatus.SC_OK);
		response.setResponseBody(resTaxiConfirmArriveDTO);
		
	}
	
	/**
	 * 
	 * @Title: confirmArriveNotice 
	 * @Description: 出租车确认到达通知类 
	 * @param taxiOrdert 出租车订单信息
	 * @author YHQ 
	 * @version V2.3.0
	 * @return void    返回类型
	 * 
	 */
	@Transactional(readOnly=true)
	public void confirmArriveNotice(UserTaxiOrdert taxiOrdert,Integer clientType){
		
		//获取出租车确认到达推送内容
		PushTaxiConfirmArrival taxiConfirmArrival = null;
		
		if(clientType == null || clientType == 2){
			taxiConfirmArrival = taxiConfirmArriveFacade.getPushConfirmArrival(taxiOrdert.getPlaceOrderUserId(), taxiOrdert.getGrabOrderUserId());
		}else{
			taxiConfirmArrival = taxiConfirmArriveFacade.getPushTaxiConfirmArrival(taxiOrdert.getPlaceOrderUserId(), taxiOrdert.getGrabOrderUserId());
		}
		
		if(taxiConfirmArrival != null && ToolUtil.isNotBlank(taxiConfirmArrival.getDriverId())){
			
			// 订单Id
			taxiConfirmArrival.setOid(taxiOrdert.getTaxiOrdertId());
			// 订单状态
			taxiConfirmArrival.setOrderStatus(taxiOrdert.getOrderStatus());
			// 支付金额
			taxiConfirmArrival.setTotalMoney(taxiOrdert.getTotalMoney());
			// 订单类型(1:顺风车 2:出租车 3:专车4:一口价)
			taxiConfirmArrival.setPublishType(2);
			
			//发送短信
			this.sendMessage(taxiConfirmArrival);
			
			//推送消息
			this.pushMessage(taxiConfirmArrival);
			
			//通知推送
			this.pushNoticeMessage(taxiConfirmArrival);
		}
		
	}
	
	/**
	 * 
	 * 确认到达后发送短信
	 * 
	 * @Title: sendMessage  
	 * @author CHEHAUNBO
	 * 
	 */
	public void sendMessage(PushTaxiConfirmArrival taxiConfirmArrival) {

		MessageRequestsDTO messageRequestsDTO = new MessageRequestsDTO();
		messageRequestsDTO.setTelPhone(taxiConfirmArrival.getTellPhone());
		messageRequestsDTO.setMessageContent(
				MessageModel.taxiConfirmArrive(taxiConfirmArrival.getDriverName()));
		queueFacade.addMessageToQueue(JSONUtil.toJSONString(messageRequestsDTO));

	}

	/**
	 * 
	 * 确认到达后推送消息
	 * 
	 * @Title: pushMessage  
	 * @author CHEHAUNBO
	 * 
	 */
	public void pushMessage(PushTaxiConfirmArrival taxiConfirmArrival) {

		// 推送Bean
		PushData pushData = new PushData();

		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("confirmArrivalPush");
		pushData.setResponseBody(taxiConfirmArrival);

		PushRequestDTO pushRequestDTO = new PushRequestDTO();

		// 推送别名
		pushRequestDTO.setAliasId(taxiConfirmArrival.getDriverId());
		pushRequestDTO.setAlert("订单已确认到达");
		pushRequestDTO.setRoleType(RoleType.Passenger);

		// 设备类型
		if (taxiConfirmArrival.getLoginEquipment().equals("Android")) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (taxiConfirmArrival.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}

		// 消息推送类型
		pushRequestDTO.setPushType(PushType.alert_msgcontent);

		// 推送类型
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));

		queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));

	}
	
	/**
	 * 
	 * 确认到达后推送消息
	 * 
	 * @Title: pushMessage  
	 * @author CHEHAUNBO
	 * 
	 */
	public void pushNoticeMessage(PushTaxiConfirmArrival taxiConfirmArrival) {
		
		// 推送Bean
		PushData pushData = new PushData();
		
		// 推送内容
		String content = MessageModel.taxiConfirmArrive(taxiConfirmArrival.getDriverName());
		
		// 推送序号(时间戳)
		pushData.setRequestNumber(DateFormatUtil.getTimeInMillis().toString());
		// 推送时间
		pushData.setRequestTime(DateFormatUtil.yyyy_MM_dd_HHmmss());
		// 模块
		pushData.setModular("newsNoticePush");
		pushData.setResponseBody(PushModel.noticeModel(1, content, null));
		
		PushRequestDTO pushRequestDTO = new PushRequestDTO();
		
		// 推送别名
		pushRequestDTO.setAliasId(taxiConfirmArrival.getDriverId());
		
		// 设备类型
		if (taxiConfirmArrival.getLoginEquipment().equals("Android")) {
			pushRequestDTO.setClientType(ClientType.Android);
		} else if (taxiConfirmArrival.getLoginEquipment().equals("iOS")) {
			pushRequestDTO.setClientType(ClientType.iOS);
		}
		
		// 消息推送类型
		pushRequestDTO.setPushType(PushType.msgcontent);
		
		// 推送类型
		pushRequestDTO.setPushContent(JSONUtil.toJSONString(pushData));
		
		queueFacade.addPushToQueue(JSONUtil.toJSONString(pushRequestDTO));
		
	}

	
	@Override
	public void automaticConfirmArrive() {
		
		
	}

}
